//
//  MyMD5.m
//  ColleageLoan
//
//  Created by XiaoguangHu on 16/3/18.
//  Copyright © 2016年 XiaoguangHu. All rights reserved.
//

#import "MD5Util.h"
#import "CommonCrypto/CommonDigest.h"


@implementation MD5Util
+(NSString *) md5: (NSString *) inPutText
{
    const void* data=[inPutText UTF8String];
    unsigned char result[16];
    CC_MD5(data,(CC_LONG)strlen(data),result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] uppercaseString];
}

+(NSString *) urlencode: (NSString *) url
{
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                            @"@" , @"&" , @"=" , @"+" ,
                            @"$" , @"," , @"[" , @"]",
                            @"#", @"!", @"'", @"(",
                            @")", @"*", nil];
    
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" ,
                             @"%3A" , @"%40" , @"%26" ,
                             @"%3D" , @"%2B" , @"%24" ,
                             @"%2C" , @"%5B" , @"%5D",
                             @"%23", @"%21", @"%27",
                             @"%28", @"%29", @"%2A", nil];
    
    long len = [escapeChars count];
    
    NSMutableString *temp = [url mutableCopy];
    
    int i;
    for(i = 0; i < len; i++)
    {
        
        [temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i]
                              withString:[replaceChars objectAtIndex:i]
                                 options:NSLiteralSearch
                                   range:NSMakeRange(0, [temp length])];
    }
    
    NSString *out = [NSString stringWithString: temp];
    //[temp release];
    //[url release];
    return out;
}

+(NSString*)md5WithBytes:(NSString *)input{
    
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    // 1 : 创建一个MD5的对象
    
    CC_MD5_CTX md5;
    
    // 2 : 初始化MD5对象
    
    CC_MD5_Init(&md5);
    
    // 3 : 准备MD5加密
    
    CC_MD5_Update(&md5, data.bytes, (CC_LONG)data.length);
    
    // 4: 准备一个字符串数组,存储MD5加密之后的数据
    
    unsigned char resly[CC_MD5_DIGEST_LENGTH];
    
    // 5: 结束MD5的加密
    
    CC_MD5_Final(resly, &md5);
    
    NSMutableString *resulString = [NSMutableString string];
    
    for (int i = 0; i< CC_MD5_DIGEST_LENGTH; i++) {
        [resulString appendFormat:@"%02X", resly[i]];
    }
    
    DeLog(@"md5WithBytes ==== %@", resulString);
    return resulString;
}


@end
